package com.wcs.exam.dao.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wcs.exam.dao.po.TagTypeCountPO;
import com.wcs.exam.dao.TagRecordDao;
import com.wcs.exam.dao.impl.mapper.TagRecordMapper;
import com.wcs.exam.dao.impl.mapper.entity.TagRecord;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 标签使用记录 持久化实现类
 *
 * @author wcs
 * @since 2025-03-17
 */
@Repository
public class TagRecordDaoImpl extends ServiceImpl<TagRecordMapper, TagRecord> implements TagRecordDao {

    @Override
    public <R> List<R> selectObjs(Wrapper<TagRecord> wrapper, Class<R> classType) {
        List<Map<String, Object>> resultMaps = baseMapper.selectMaps(wrapper);
        if (CollectionUtil.isEmpty(resultMaps)) {
            return Collections.emptyList();
        }
        return BeanUtil.copyToList(resultMaps, classType);
    }

    @Override
    public List<TagTypeCountPO> countByTagIds(Collection<Long> tagIds) {
        LambdaQueryWrapper<TagRecord> wrapper = new QueryWrapper<TagRecord>()
                .select("tag_id as tagId, tag_record_type as tagType, count(1) as count")
                .lambda()
                .in(TagRecord::getTagId, tagIds)
                .groupBy(TagRecord::getTagId, TagRecord::getTagType);
        return selectObjs(wrapper, TagTypeCountPO.class);
    }

    @Override
    public List<TagRecord> listByTagTypeAndResourceId(Integer tagType, Long resourceId) {
        return lambdaQuery()
                .eq(TagRecord::getTagType, tagType)
                .eq(TagRecord::getResourceId, resourceId)
                .list();
    }

    @Override
    public List<TagRecord> listByTagTypeAndResourceIds(Integer tagType, List<Long> resourceIds) {
        return lambdaQuery()
                .eq(TagRecord::getTagType, tagType)
                .in(TagRecord::getResourceId, resourceIds)
                .list();
    }

    @Override
    public boolean deleteByTagTypeAndResourceId(Integer tagType, Long resourceId) {
        return lambdaUpdate()
                .eq(TagRecord::getTagType, tagType)
                .eq(TagRecord::getResourceId, resourceId)
                .remove();
    }

    @Override
    public boolean deleteByTagId(Long tagId) {
        return lambdaUpdate()
                .eq(TagRecord::getTagId, tagId)
                .remove();
    }
}
